deleteArray
Arrays Sandbox PanosP Revised

Deleting Elements from an Array

Problem
=======

Is there a way to delete (remove) array elements, or arrays as a whole?

Solution
========

You can delete any element of an array if, of course, you know the
element's index (key), e.g. to delete the `"panos"` indexed element
of the array `users`:

  delete users["panos"]

There's no problem trying to delete an element that doesn't exist,
or even trying to delete an "element" of a non existent array,
but, if this is the case, the name of the array cannot longer be
used for any scalar or name of a function.

To delete the array `users` as a whole, just:

  delete users

that is delete the array without specify an index.

Discussion
==========

Scope of Array Names
--------------------

After deleting an array as a whole,
you cannot use the same name for a scalar variable;
the name has been "marked" as an array name by awk (permanently), so
you can only use that name for a new array, nothing else.
If you delete an array that doesn't even exist, then
the name specified is "remembered" by awk as an array,
you can't use that name for anything else but an array.

Delete First, Then Add New Entries
----------------------------------

When constructing functions that fill array elements, e.g. the
`split` builtin awk function, then don't forget to
delete the array before starting indexing new array elements.
If the array passed contains any elements
the time it's passed to the function, then these elements will,
of course, remain as array elements, mixed with the
new elements added by the function. Let's make that
point clear using an example. The code below is
a function that accepts a user name and fills
an array with information about the user just
taken from `/etc/passwd` file. The indices to
be used are:

+ uid (user id, the 3rd field)
+ gid (group id, the 4rd field)
+ info (full name, or other information, the 5th field)
+ home (home directory, the 6th field)
+ shell (shell program, the 7th field)

 function get_user_info(name, data,		ufile, ofs, found) {
 	delete data	# don't forget
 	found = 0
 	ufile = "/etc/passwd"
 	ofs = FS
 	FS = ":"
 	while ((getline <ufile) > 0) {
 		if ($1 == name) {
 			data["uid"] = $3
 			data["gid"] = $4
 			data["info"] = $5
 			data["home"] = $6
 			data["shell"] = $7
 			found = 1
 			break
 		}
 	}
 	close(ufile)
 	FS = ofs
 	return(found)
 }

Failing to call `delete data` in the beging of the funtion, the `data`
array may have elements already filled by previous calls to that same
(or other) function. Of course, you can check the returned value
(`found`) to check when the user were found or not in the password file,
but it's very risky to leave such arrays undeleted before start filling
them up.

Author
======

Panos Papadopoulos

